package com.ruoyi.common.utils;

import org.apache.commons.collections.MapUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;

/**
 * Map通用处理方法
 *
 * @author ruoyi
 */
public class MapDataUtil {
    public static Map<String, Object> convertDataMap(HttpServletRequest request) {
        Map<String, String[]> properties = request.getParameterMap();
        Map<String, Object> returnMap = new HashMap<>(properties.size());
        Iterator<?> entries = properties.entrySet().iterator();
        Map.Entry<?, ?> entry;
        String name = "";
        String value = "";
        while (entries.hasNext()) {
            entry = (Entry<?, ?>) entries.next();
            name = (String) entry.getKey();
            Object valueObj = entry.getValue();
            if (null == valueObj) {
                value = "";
            } else if (valueObj instanceof String[]) {
                String[] values = (String[]) valueObj;
                for (int i = 0; i < values.length; i++) {
                    value = values[i] + ",";
                }
                value = value.substring(0, value.length() - 1);
            } else {
                value = valueObj.toString();
            }
            returnMap.put(name, value);
        }
        return returnMap;
    }


    /**
     * 合并 srcMap 到 destMap 中
     *
     * @param srcMap
     * @param destMap
     */
    public static Map<String, Object> mergeProps(Map<String, Object> srcMap, Map<String, Object> destMap) {
        if (MapUtils.isEmpty(srcMap)) {
            return destMap;
        }
        for (Map.Entry<String, Object> entry : srcMap.entrySet()) {
            Object value = entry.getValue();
            if (value == null) {
                continue;
            }
            if (destMap.get(entry.getKey()) == null) {
                destMap.put(entry.getKey(), entry.getValue());
                continue;
            }
            if (value instanceof Map) {
                mergeProps((Map<String, Object>) value, (Map<String, Object>) destMap.get(entry.getKey()));
            } else {
                destMap.put(entry.getKey(), entry.getValue());
            }
        }
        return destMap;
    }

}
